package com.zsl.controller.User;

import com.alibaba.fastjson.JSON;
import com.zsl.service.BookService;
import com.zsl.service.OrderInfoService;
import com.zsl.service.impl.BookServiceImpl;
import com.zsl.service.impl.OrderInfoServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "OpOrderItem", urlPatterns = "/op/order/item")
public class OpOrderItem extends HttpServlet {
    private final BookService bookService = new BookServiceImpl();
    private final OrderInfoService orderInfoService=new OrderInfoServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取数据
        String b_id = request.getParameter("b_id").equals("") ? null : request.getParameter("b_id");
        String b_num = request.getParameter("b_num").equals("") ? null : request.getParameter("b_num");
        //TODO 这个是测试用户，之后的用户会从Session中获取
        HttpSession session = request.getSession();
        String u_id=(String) session.getAttribute("id");
        Map<String, Object> res = new HashMap<>();
        if (bookService.isNull(new String[]{b_id, b_num,u_id})) {
            res.put("code", "0");
            res.put("msg", "未知参数错误");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(res));
        } else {
            //执行相关操作
            Map<String,Object> input=new HashMap<>();
            input.put("u_id",u_id);
            input.put("b_id",b_id);
            input.put("b_num",b_num);
            try {
                orderInfoService.opItemIntoShoppingCart(input);
                res.put("code", "1");
                res.put("msg", "更新成功");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
                System.out.println("出错问题~~~");
                res.put("code", "0");
                res.put("msg", "更新失败");
            }finally {
                PrintWriter out = response.getWriter();
                out.write(JSON.toJSONString(res));
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
